/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package carrello.impl.boundary.administrator;

import carrello.exception.CarrelloException;
import carrello.impl.boundary.AbstractUI;
import carrello.impl.controller.administrator.AddProductCTRL;
import carrello.model.entities.Category;
import carrello.model.entities.Product;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;


/**
 *
 * @author Usman
 */
public class AddProductUI extends AbstractUI {
    private final String path = "/home/grads/haseeb/public_html/carrello/";
    private LinkedList<LinkedList<String>> newproductKeys;
    private List<String> newproductValues;
    private String categoryid;
    private Product product;
    private String error;
    private String categories;
    private File image;
    private int change;

    public void seterror ( String s ) {
        error = s;
    }
    public String geterror () {
        return error;
    }
    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }
    
    public int getchange () {
        return change;
    }
    public void setchange ( int c ) {
        change = c;
    }
    public String getcategories () {
        return categories;
    }
    public void setcategories (String s) {
        categories = s;
    }
    public Product getProduct () {
        return product;
        
    }
    private void fetchProductKeys ( ) {
        newproductKeys = AddProductCTRL.fetchProductProperties ( categoryid );
    }
    public LinkedList<LinkedList<String>> getAttributes () {
        return newproductKeys;
    }

    public void setValues ( String[] att ) {
        if ( newproductValues == null )
            newproductValues = new ArrayList<String> ();

        for ( String s: att )
            newproductValues.add(s);
    }
    public void setcategoryid ( String c ) {
        categoryid = c;
    }
    public String getcategoryid () {
        return categoryid;
    }
    @Override
    public String execute () {

        if ( !getSessionIsLoggedIn())
            return ERROR;
        fetchCategories ();
        
        if ( newproductKeys == null )
            fetchProductKeys();


        if ( change == 1 || newproductValues == null)
        {
            change = 0;
            return INPUT;
        }
        try {
            addProduct ();
        } catch (Exception ex) {
            if (ex instanceof NullPointerException) {
                seterror("Added product with no image");
                return "duplicate";
            }
            Logger.getLogger(AddProductUI.class.getName()).log(Level.SEVERE, null, ex);
            seterror(ex.getMessage());
            return "duplicate";
        }
        return SUCCESS;
        
    }
    private void addProduct () throws Exception{
        try {
            product = new Product ();
            product.setName(newproductValues.get(0));
            product.setDescription(newproductValues.get(1)); 
            product.setPrice(newproductValues.get(2));
            product.setManufacturer(newproductValues.get(3));
            product.setQuantity(Integer.parseInt(newproductValues.get(4)));
            product.setCatalogId(Integer.parseInt(newproductValues.get(5)));
            Category c = AddProductCTRL.getCategory (categoryid);
            product.setCategory (c);
            Map<String, String> map = new HashMap <String, String> ();
            for ( int i = 6; i < newproductKeys.size(); i++)
                map.put (newproductKeys.get(i).get(0), newproductValues.get(i));
            AddProductCTRL.addProduct ( product, map );
            getImage(image , product);
        } catch (CarrelloException ex) {
            throw ex;
        }
    }

    private void getImage(File image, Product product) throws Exception
    {
        int pid = product.getProduct_id();
        File productImage = new File(path + pid + ".jpg");
        try {
            FileUtils.copyFile(image, productImage);
            System.out.println(productImage.getAbsoluteFile());
        } catch (Exception ex) {
            Logger.getLogger(AddProductUI.class.getName()).log(Level.SEVERE, null, ex);
            throw ex;
        }
    }
    private void addCategory ( Category c, StringBuilder str, String i ) {
        if ( categoryid != null && categoryid.equalsIgnoreCase(c.getName()))
            str.append ("<option selected=\"true\" value=\""+ c.getName() +"\">"+ i + " "+c.getName()+"</option>");
        else
            str.append ("<option value=\""+ c.getName() +"\">"+ i + " "+c.getName()+"</option>");
        int count = 1;
        if ( c.getchildren() == null )
            return;
        for ( Category cat: c.getchildren()) {
            addCategory ( cat, str, i + "."+ String.valueOf(count));
            ++count;
            }
        }
        
    private void fetchCategories() {
        Category cat = AddProductCTRL.getCategory("All");
        StringBuilder str = new StringBuilder ();
        int i = 1;
        addCategory(cat, str, "1");  
        categories = str.toString();
    }
}